<?php

require_once dirname(dirname(__FILE__)).'/class/gtickets.php' ;
require_once dirname(dirname(__FILE__)).'/include/common_functions.php' ;
$myts =& MyTextSanitizer::getInstance() ;
$db =& Database::getInstance() ;

// THIS PAGE CAN BE CALLED ONLY FROM D3DOWNLOADS
if( $xoopsModule->getVar('dirname') != $mydirname ) die( 'this page can be called only from '.$mydirname ) ;

// PERMISSION ERROR
$module_handler =& xoops_gethandler( 'module' ) ;
$module =& $module_handler->getByDirname( $mydirname ) ;
$moduleperm_handler =& xoops_gethandler( 'groupperm' ) ;
$mid = $module->getVar('mid') ;
if( ! is_object( @$xoopsUser ) || ! $moduleperm_handler->checkRight( 'module_admin' , $mid , $xoopsUser->getGroups() ) ) {
	die( 'Only administrator can use this feature.' ) ;
}

$cid = isset($_GET['cid']) ? intval($_GET['cid']) : "";

// GET CATEGORY DATA
$categorydata = array();
if( empty( $cid ) ){
	$sql = "SELECT COUNT(*) FROM ".$db->prefix( $mydirname."_cat" )."";
	list( $count ) = $db->fetchRow( $db->query( $sql ) );
	$categorydata = array(
		'cat_weight' =>  $count ,
	) ;
} else {
	$result = $db->query("SELECT cid, pid, title, imgurl, shotsdir, cat_weight, submit_message FROM ".$db->prefix( $mydirname."_cat" )." WHERE cid = '".$cid."'");
	while( list( $c_id, $p_id, $name, $img, $shots, $weight, $submit_message ) = $db->fetchRow( $result ) ) {
		$categorydata = array(
			'cid' => $c_id ? intval( $c_id ) :"" ,
			'pid' => $p_id ? intval( $p_id ) :"" ,
			'title' => $name ? $myts->makeTboxData4Edit( $name ) :"" ,
			'imgurl' => $img ? $myts->makeTboxData4Edit( $img ) :"" ,
			'shotsdir' => $shots ? $myts->makeTboxData4Edit( $shots ) :"" ,
			'cat_weight' =>  $cid ? intval( $weight ) : 0 ,
			'submit_message' => $submit_message ? $myts->makeTboxData4Edit( $submit_message ) :"" ,
		) ;
	}
}

$useshots = ! empty( $xoopsModuleConfig['useshots'] ) ? 1 : 0 ;
$usealbum = d3download_can_albumselect( $mydirname ) ;
if( ! empty( $useshots ) ){
	if( empty( $usealbum ) ){
		$can_selectshotsdir = 1;
	} else {
		$can_selectshotsdir = 0;
	}
} else {
	$can_selectshotsdir = 0;
}

$shots_dir = XOOPS_ROOT_PATH.'/modules/'.$mydirname.'/images/shots/';
$shotsdirhelp = sprintf( _MD_D3DOWNLOADS_CATEGORYSHOTSDIRHELP , $shots_dir );

// MAIN CATEGORY LIST
include_once dirname(dirname(__FILE__)).'/class/mytree.php' ;
$mytree = new MyTree( $db->prefix( $mydirname."_cat" ) , "cid" , "pid" ) ;
$maincategory = array( 0 => '--' ) ;
$result = $db->query("SELECT cid, title  FROM ".$db->prefix( $mydirname."_cat" )." WHERE pid='0' AND cid NOT IN ( '".$cid."' ) ORDER BY cat_weight");
while( list( $id, $name ) = $db->fetchRow( $result ) ) {
	$catid = intval( $id );
	$maincategory[ $catid ] = $myts->makeTboxData4Edit( $name ) ;
	$arr = $mytree->getChildTreeArray( $catid );
	foreach ( $arr as $child ) {
		$child_id = intval( $child['cid'] );
		if( $child_id != $cid ){
			$child['prefix'] = str_replace(".","--",$child['prefix']);
			$maincategory[ $child_id ] = $child['prefix']."&nbsp;".$myts->makeTboxData4Edit( $child['title'] );
		}
	}
}

// GROUP FORM
$group_handler =& xoops_gethandler( 'group' ) ;
$groups =& $group_handler->getObjects() ;
$group_trs = '' ;
foreach( $groups as $group ) {
	$gid = $group->getVar('groupid') ;
	$fars = $db->query( "SELECT  can_read, can_post, can_edit, can_delete, post_auto_approved, edit_auto_approved, html FROM ".$db->prefix( $mydirname."_user_access" )." WHERE groupid=".$group->getVar('groupid')." AND cid=$cid" ) ;
	if( $db->getRowsNum( $fars ) > 0 ) {
		list( $can_read, $can_post , $can_edit , $can_delete , $post_auto_approved , $edit_auto_approved , $html ) = $db->fetchRow( $fars ) ;
	} else {
		if( $gid == intval( XOOPS_GROUP_ADMIN ) ){
			$can_read = $can_post = $can_edit = $can_delete = $post_auto_approved = $edit_auto_approved = true ;
			$html = false ;
		} elseif( $gid == intval( XOOPS_GROUP_USERS ) ){
			$can_read = true ;
			$can_post = $can_edit = $can_delete = $post_auto_approved = $edit_auto_approved = $html = false ;
		} else {
			$can_read = $can_post = $can_edit = $can_delete = $post_auto_approved = $edit_auto_approved = $html = false ;
		}
	}
	$can_read_checked = $can_read ? "checked='checked'" : "" ;
	$can_post_checked = $can_post ? "checked='checked'" : "" ;
	$can_edit_checked = $can_edit ? "checked='checked'" : "" ;
	$can_delete_checked = $can_delete ? "checked='checked'" : "" ;
	$post_auto_approved_checked = $post_auto_approved ? "checked='checked'" : "" ;
	$edit_auto_approved_checked = $edit_auto_approved ? "checked='checked'" : "" ;
	$html_checked = $html ? "checked='checked'" : "" ;
	$group_trs .= "
		<tr>
			<td class='even'>".$group->getVar('name')."</td>
			<td class='even'><input type='checkbox' name='can_read[$gid]' id='gcol_1_{$gid}' value='1' $can_read_checked /></td>
			<td class='even'><input type='checkbox' name='can_posts[$gid]' id='gcol_2_{$gid}' value='1' $can_post_checked /></td>
			<td class='even'><input type='checkbox' name='can_edits[$gid]' id='gcol_3_{$gid}' value='1' $can_edit_checked /></td>
			<td class='even'><input type='checkbox' name='can_deletes[$gid]' id='gcol_4_{$gid}' value='1' $can_delete_checked /></td>
			<td class='even'><input type='checkbox' name='post_auto_approveds[$gid]' id='gcol_5_{$gid}' value='1' $post_auto_approved_checked /></td>
			<td class='even'><input type='checkbox' name='edit_auto_approved[$gid]' id='gcol_6_{$gid}' value='1' $edit_auto_approved_checked /></td>
			<td class='even'><input type='checkbox' name='html[$gid]' id='gcol_7_{$gid}' value='1' $html_checked /></td>
		</tr>\n" ;
}

// TRANSACTION PART

if( isset( $_POST['categoryform_post'] ) ) {
	if ( ! $xoopsGTicket->check( true , 'd3downloads' ) ) {
		redirect_header(XOOPS_URL.'/modules/'.$mydirname.'/admin/index.php',3,$xoopsGTicket->getErrors());
	}

	$edit_id = isset( $_POST['cid'] ) ? intval( @$_POST['cid'] ) : 0 ;
	$title  = isset( $_POST['title'] )  ? $myts->makeTboxData4Save( @$_POST['title'] ) : "" ;
	$imgurl = isset( $_POST['imgurl'] ) ? $myts->makeTboxData4Save( @$_POST['imgurl'] ) : "" ;
	$shotsdir = isset( $_POST['shotsdir'] ) ? $myts->makeTboxData4Save( @$_POST['shotsdir'] ) : "" ;
	$cat_weight = isset( $_POST['cat_weight'] ) ? intval( @$_POST['cat_weight'] ) : "" ;
	$submit_message = isset( $_POST['submit_message'] ) ? $myts->makeTboxData4Save( @$_POST['submit_message'] ) : "" ;
	$pid = isset( $_POST['maincategory'] ) ?  intval( @$_POST['maincategory'] ) : 0 ;

	// ERORR INITIALIZATION
	$errors = '';

	// NO Data
	if( ! $title ){
		$stop .= true ;
		redirect_header( XOOPS_URL."/modules/$mydirname/admin/index.php?page=scriptedit&amp;cid=".$cid, 2, _MD_D3DOWNLOADS_NO_DATA);
	}

	// MAKE LINK SQL
	if( empty( $edit_id ) ) {
		list( $newid ) = $db->fetchRow( $db->query( "SELECT MAX( cid ) + 1 FROM ".$db->prefix( $mydirname."_cat" ) ) ) ;
		$sql  = "INSERT INTO ".$db->prefix($mydirname."_cat")." ( cid, pid, title, imgurl, shotsdir, cat_weight, submit_message ) ";
		$sql .= "VALUES( '".$newid."', '".$pid."','".$title."', '".$imgurl."', '".$shotsdir."', '".$cat_weight."', '".$submit_message."' )"; 
		$result = $db->query($sql);
		$new_cid = $db->getInsertId();
		if( empty( $new_cid ) ){
			redirect_header( XOOPS_URL."/modules/$mydirname/admin/index.php?page=categorymanager" , 2 , _MD_D3DOWNLOADS_ERROR_MESSEAGE_NOID ) ;
			exit();
		} elseif( empty( $pid ) ) {
			$result = $db->query( "SELECT groupid FROM ".$db->prefix("groups") ) ;
			while( list( $gid ) = $db->fetchRow( $result ) ) {
				$can_read = empty( $_POST['can_read'][$gid] ) ? 0 : 1 ;
				$can_post = empty( $_POST['can_posts'][$gid] ) ? 0 : 1 ;
				$can_edit = empty( $_POST['can_edits'][$gid] ) ? 0 : 1 ;
				$can_delete = empty( $_POST['can_deletes'][$gid] ) ? 0 : 1 ;
				$post_auto_approved = empty( $_POST['post_auto_approveds'][$gid] ) ? 0 : 1 ;
				$edit_auto_approved = empty( $_POST['edit_auto_approved'][$gid] ) ? 0 : 1 ;
				$html = empty( $_POST['html'][$gid] ) ? 0 : 1 ;
				$sql="INSERT INTO ".$db->prefix( $mydirname."_user_access" )." SET cid=$new_cid, groupid=$gid, can_read=$can_read, can_post=$can_post, can_edit=$can_edit, can_delete=$can_delete, post_auto_approved=$post_auto_approved, edit_auto_approved=$edit_auto_approved, html=$html";
				$res = $db->query($sql);
				if( ! $res ) $errors[] = $new_cid ;
			}
		}
		// Define tags for notification message
		$tags = array();
		$tags = array(
			'CAT_TITLE' => $title ,
			'CAT_URL' => XOOPS_URL . '/modules/' . $mydirname . '/index.php?cid=' . $new_cid ,
		) ;
		d3download_main_trigger_event( 'global' , 0 , 'newcategory' , $tags, 0 ) ;
	} elseif ( empty( $stop ) && ! empty( $edit_id ) ) {
		// DOES THE LINK ALREADY EXIST? -- UPDATE SQL
		$sql = "SELECT COUNT(*) FROM ".$db->prefix( $mydirname."_cat" )." WHERE cid='".$edit_id."'";
		list( $count ) = $db->fetchRow( $db->query( $sql) );
		if( $count > 0 ){
			$sql = "UPDATE ".$db->prefix($mydirname."_cat")." SET pid = '".$pid."', title = '".$title."', imgurl = '".$imgurl."', shotsdir = '".$shotsdir."', cat_weight = '".$cat_weight."', submit_message = '".$submit_message."' WHERE cid = ".$edit_id;
			$result = $db->query($sql);
			if( ! $result ) $errors[] = $edit_id ;
			$db->query( "DELETE FROM ".$db->prefix($mydirname."_user_access")." WHERE cid=$edit_id AND groupid>0" ) ;
			$result = $db->query( "SELECT groupid FROM ".$db->prefix("groups") ) ;
			$errors = array();
			if( empty( $pid ) ){
				while( list( $gid ) = $db->fetchRow( $result ) ) {
					$can_read = empty( $_POST['can_read'][$gid] ) ? 0 : 1 ;
					$can_post = empty( $_POST['can_posts'][$gid] ) ? 0 : 1 ;
					$can_edit = empty( $_POST['can_edits'][$gid] ) ? 0 : 1 ;
					$can_delete = empty( $_POST['can_deletes'][$gid] ) ? 0 : 1 ;
					$post_auto_approved = empty( $_POST['post_auto_approveds'][$gid] ) ? 0 : 1 ;
					$edit_auto_approved = empty( $_POST['edit_auto_approved'][$gid] ) ? 0 : 1 ;
					$html = empty( $_POST['html'][$gid] ) ? 0 : 1 ;
					$sql="INSERT INTO ".$db->prefix( $mydirname."_user_access" )." SET cid=$edit_id, groupid=$gid, can_read=$can_read, can_post=$can_post, can_edit=$can_edit, can_delete=$can_delete, post_auto_approved=$post_auto_approved, edit_auto_approved=$edit_auto_approved, html=$html";
					$res = $db->query($sql);
					if( ! $res ) $errors[] = $edit_cid ;
				}
			}
		}
	}
	redirect_header( XOOPS_URL."/modules/$mydirname/admin/index.php?page=categorymanager" , 2 , $errors ? sprintf( _MD_D3DOWNLOADS_ERROR_MESSEAGE , $errors ) : _MD_D3DOWNLOADS_REGSTERED ) ;
	exit();
}
// DELETE SQL
if( isset( $_POST['categoryform_delete'] ) ) {
	$errors = "";
	$cid = isset( $_POST['cid'] ) ? intval( @$_POST['cid'] ) : "" ;
	d3download_delcat( $mydirname , $cid , $errors);
	redirect_header( XOOPS_URL."/modules/$mydirname/admin/index.php?page=categorymanager" , 2 , $errors ? sprintf( _MD_D3DOWNLOADS_ERROR_MESSEAGE , $errors ) : _MD_D3DOWNLOADS_DELETED ) ;
	exit();
}

// DISPLAY STAGE

xoops_cp_header();
include dirname(__FILE__).'/mymenu.php' ;
require_once XOOPS_ROOT_PATH.'/class/template.php' ;
$tpl =& new XoopsTpl() ;
$tpl->assign( array(
	'mydirname' => $mydirname ,
	'mod_url' => XOOPS_URL.'/modules/'.$mydirname ,
	'page' => 'categoryedit' ,
	'categorydata' => $categorydata ,
	'maincategory' => $maincategory ,
	'group_trs' => $group_trs ,
	'can_selectshotsdir' => $can_selectshotsdir ,
	'shotsdirhelp' => $shotsdirhelp ,
	'gticket_hidden' => $xoopsGTicket->getTicketHtml( __LINE__ , 1800 , 'd3downloads') ,
) ) ;
$tpl->display( 'db:'.$mydirname.'_admin_category_edit.html' ) ;
xoops_cp_footer();

?>